using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using AjGenesisStudio.Properties;

namespace AjGenesisStudio.Commands
{
    class SaveCommand : Command
    {

        public override bool Execute()
        {
            return Execute(Global.Instance.MainForm.GetActiveDocument());
        }

        public bool Execute(Documents.Document doc)
        {
            if (doc == null)
                return true;

            if (!doc.editor.Saved)
            {
                if (string.IsNullOrEmpty(doc.FilePath))
                {
                    string file = ShowSave(doc.DefaultExtension);

                    Global.Instance.StartWork("Saving " + Path.GetFileName(file));

                    if (!string.IsNullOrEmpty(file))
                    {
                        doc.editor.Save(file);
                        doc.FilePath = file;
                    }
                }
                else
                {
                    Global.Instance.StartWork("Saving " + Path.GetFileName(doc.FilePath));
                    doc.editor.Save(doc.FilePath);
                }
            }

            Global.Instance.EndWork();

            return true;
        }

        public static string ShowSave(string defext)
        {
            string filters = string.Empty;
            SaveFileDialog dlg = new SaveFileDialog();

            if (defext.StartsWith("."))
                defext = defext.Remove(0, 1);

            dlg.DefaultExt = defext;
            if (!string.IsNullOrEmpty(Settings.Default.LastProject))
                dlg.InitialDirectory = Settings.Default.LastProject;

            switch (defext)
            {
                case "tpl":
                    filters = "AjGenesis Template (*.tpl)|*.tpl|";
                    break;
                case "ajg":
                    filters = "AjGenesis Task (*.ajg)|*.ajg|";
                    break;
                case "xml":
                    filters = "XML Document (*.xml)|*.xml|";
                    break;
                case "bat":
                    filters = "DOS Batch (*.bat)|*.bat|";
                    break;
                case "build":
                    filters = "NAnt build file (*.build)|*.build|";
                    dlg.FileName = "default.build";
                    break;
                default:
                    filters = string.Format("{1} file (*.{0})|*.{0}|", defext, defext.ToUpper());
                    break;
            }
            dlg.Filter = filters + "Any file (*.*)|*.*";

            if (dlg.ShowDialog() == DialogResult.OK)
                return dlg.FileName;
            else
                return string.Empty;
        }
    }
}
